const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const { initDb, getDb } = require('./database');

const app = express();
app.use(bodyParser.json({ limit: '10mb' }));

// 用户会话存储
const userSessions = new Map();

// 基本认证中间件
const basicAuth = async (req, res, next) => {
    try {
        const authHeader = req.headers.authorization;
        
        if (!authHeader || !authHeader.startsWith('Basic ')) {
            return res.status(401).json({ message: '需要认证' });
        }

        const credentials = Buffer.from(authHeader.slice(6), 'base64').toString().split(':');
        const [username, password] = credentials;

        const db = getDb();
        const user = await db.get('SELECT * FROM users WHERE username = ?', [username]);

        if (!user || user.password !== password) {
            console.log('认证失败:', username);
            return res.status(401).json({ message: '用户名或密码错误' });
        }

        // 确保用户目录存在
        const userDir = path.join(__dirname, 'uploads', username);
        if (!fs.existsSync(userDir)) {
            fs.mkdirSync(userDir, { recursive: true });
        }

        // 只在会话不存在时初始化会话
        if (!userSessions.has(username)) {
            userSessions.set(username, {
                currentDir: userDir,
                rootPath: userDir
            });
            console.log('用户会话已初始化:', username);
        }

        req.user = {
            username,
            rootPath: userDir,
            session: userSessions.get(username)
        };

        console.log('用户认证成功:', username);
        console.log('当前目录:', req.user.session.currentDir);
        next();
    } catch (err) {
        console.error('认证错误:', err);
        res.status(500).json({ message: '认证过程出错' });
    }
};
// 应用认证中间件
app.use(basicAuth);

// 确保用户目录存在
const ensureUserDir = (username) => {
    const userDir = path.join(__dirname, 'uploads', username);
    if (!fs.existsSync(userDir)) {
        fs.mkdirSync(userDir, { recursive: true });
    }
    return userDir;
};

// 上传文件
app.post('/upload', (req, res) => {
    const { filename, data } = req.body;
    const { username, session } = req.user;

    if (!filename || !data) {
        return res.status(400).json({ message: '需要提供文件名和数据' });
    }

    try {
        const filePath = path.join(session.currentDir, path.basename(filename));
        const buffer = Buffer.from(data, 'base64');
        fs.writeFileSync(filePath, buffer);
        res.json({ message: '文件上传成功' });
    } catch (err) {
        console.error('上传错误:', err);
        res.status(500).json({ message: '文件上传失败', error: err.message });
    }
});

// 下载文件
app.get('/download/:filename', (req, res) => {
    const { filename } = req.params;
    const { session } = req.user;

    try {
        const filePath = path.join(session.currentDir, filename);
        if (!fs.existsSync(filePath)) {
            return res.status(404).json({ message: '文件不存在' });
        }

        const data = fs.readFileSync(filePath);
        res.json({
            message: '文件下载成功',
            data: data.toString('base64')
        });
    } catch (err) {
        res.status(500).json({ message: '文件下载失败', error: err.message });
    }
});

// 修改删除接口以支持递归删除目录
app.delete('/delete/:name', (req, res) => {
    const { name } = req.params;
    const { session } = req.user;

    try {
        const targetPath = path.join(session.currentDir, name);
        if (!fs.existsSync(targetPath)) {
            return res.status(404).json({ message: '文件或目录不存在' });
        }

        const stats = fs.statSync(targetPath);
        if (stats.isDirectory()) {
            // 使用递归删除目录
            fs.rmSync(targetPath, { recursive: true, force: true });
            res.json({ message: '目录删除成功' });
        } else {
            // 删除文件
            fs.unlinkSync(targetPath);
            res.json({ message: '文件删除成功' });
        }
    } catch (err) {
        console.error('删除错误:', err);
        res.status(500).json({ 
            message: '删除操作失败',
            error: err.message
        });
    }
});

// 重命名文件
app.post('/rename', (req, res) => {
    const { oldName, newName } = req.body;
    const { session } = req.user;

    try {
        const oldPath = path.join(session.currentDir, oldName);
        const newPath = path.join(session.currentDir, newName);

        if (!fs.existsSync(oldPath)) {
            return res.status(404).json({ message: '源文件不存在' });
        }

        fs.renameSync(oldPath, newPath);
        res.json({ message: '文件重命名成功' });
    } catch (err) {
        res.status(500).json({ message: '重命名失败', error: err.message });
    }
});

// 创建目录
app.post('/mkdir', (req, res) => {
    const { dirname } = req.body;
    const { session } = req.user;

    try {
        const dirPath = path.join(session.currentDir, dirname);
        fs.mkdirSync(dirPath, { recursive: true });
        res.json({ message: '目录创建成功' });
    } catch (err) {
        res.status(500).json({ message: '创建目录失败', error: err.message });
    }
});

// 列出目录内容
app.get('/list', (req, res) => {
    const { session } = req.user;

    try {
        console.log('正在读取目录:', session.currentDir);
        const items = fs.readdirSync(session.currentDir).map(name => {
            const fullPath = path.join(session.currentDir, name);
            const stats = fs.statSync(fullPath);
            return {
                name: stats.isDirectory() ? `${name}/` : name,
                isDirectory: stats.isDirectory()
            };
        });

        res.json({ items });
    } catch (err) {
        console.error('读取目录错误:', err);
        res.status(500).json({ 
            message: '读取目录失败',
            error: err.message,
            path: session.currentDir
        });
    }
});

// 切换目录
app.post('/cd', (req, res) => {
    const { path: targetPath } = req.body;
    const { session, rootPath, username } = req.user;

    try {
        let newPath;
        if (path.isAbsolute(targetPath)) {
            // 对于绝对路径，需要确保在用户的根目录内
            const normalizedTargetPath = path.normalize(targetPath);
            const pathWithoutDrive = normalizedTargetPath.replace(/^[a-zA-Z]:/, '');
            newPath = path.join(rootPath, pathWithoutDrive);
        } else {
            // 对于相对路径，与当前目录合并
            newPath = path.join(session.currentDir, targetPath);
        }

        // 创建目录（如果不存在）
        if (!fs.existsSync(newPath)) {
            fs.mkdirSync(newPath, { recursive: true });
        }

        // 获取文件状态并检查是否为目录
        const stats = fs.statSync(newPath);
        if (!stats.isDirectory()) {
            return res.status(400).json({ message: '目标不是目录' });
        }

        // 确保新路径在用户的根目录内
        if (!newPath.startsWith(rootPath)) {
            return res.status(403).json({ message: '无权访问该目录' });
        }

        // 更新会话中的当前目录
        session.currentDir = newPath;
        // 同时更新全局会话存储
        userSessions.set(username, session);

        console.log('目录切换信息:', {
            username,
            oldPath: session.currentDir,
            newPath,
            targetPath
        });

        res.json({ message: '目录切换成功', path: targetPath });
    } catch (err) {
        console.error('切换目录错误:', err);
        res.status(500).json({ message: '切换目录失败', error: err.message });
    }
});

// 获取当前目录
app.get('/pwd', (req, res) => {
    const { session, rootPath } = req.user;
    try {
        // 返回绝对路径
        const absolutePath = session.currentDir;
        console.log('当前目录信息:', {
            rootPath,
            currentDir: absolutePath
        });
        res.json({ path: absolutePath });
    } catch (err) {
        console.error('获取当前目录错误:', err);
        res.status(500).json({ message: '获取当前目录失败', error: err.message });
    }
});

const PORT = 8080;
app.listen(PORT, () => {
    initDb();
    console.log(`服务器运行在 http://localhost:${PORT}`);
});